define(['app', 'rcss!css/timeline'], function(app) {
    app.controller('BlogViewerController', function($http, $scope, $routeParams, $timeout, $anchorScroll, toastr) {
        var self = this;
        self.title = '';
        self.code = '';
        self.headers = [];
        self.selected = '';
        self.fullScreen = false;
        self.showHeaders = false;

        var blogid = $routeParams.blogid,
            anchorScrolled = true;

        self.init = function() {
            // Render view
            $('body').addClass('x-blog-view');
            // Load blog
            if (blogid) {
                $http.get('/blog/blogs.json').then(function(response) {
                    var article = _.find(response.data.articles, function(article) {
                        return article.id == blogid;
                    });
                    if (article) {
                        self.title = article.title;
                    }
                });
                $http.get('/blog/articles/' + blogid + '.md').then(function(response) {
                    if (response.status == 200) {
                        self.code = response.data;
                        $timeout(function() {
                            var headers = [],
                                jqHeaders = _.map(_.filter($('.x-markdown>p [id^="section-"]'), function(e) {
                                    return e.innerText.trim() !== '';
                                }), function(header) {
                                    return $(header);
                                });
                            _.forEach(jqHeaders, function(header) {
                                headers.push({
                                    id: header.attr('id'),
                                    text: header.text().trim(),
                                    level: header.prop('tagName').toLowerCase()
                                });
                            });
                            self.headers = headers;
                            // Sync body scroll
                            if (!_.isEmpty(jqHeaders)) {
                                $timeout(function() {
                                    syncBodyScroll(jqHeaders);
                                });
                            }
                        }, 200);
                    }
                });
            } else {
                toastr.error('您阅读的博客不存在！');
            }
        }

        function syncBodyScroll(jqHeaders) {
            $(window).scroll(function() {
                if (anchorScrolled) {
                    var jqContainer = $(window);
                    var scrollTop = $(window).scrollTop();
                    for (var i = 0; i < jqHeaders.length; i++) {
                        var headerTop = jqHeaders[i].position().top + jqHeaders[i].height();
                        if (headerTop >= scrollTop) {
                            var index = i + 1;
                            $('.x-header-list li').each(function(j) {
                                if (j == index) {
                                    $(this).addClass('x-active');
                                } else {
                                    $(this).removeClass('x-active');
                                }
                            });
                            var iHeader = $('.x-header-list li:eq(' + index + ')'),
                                lHeader = $('.x-header-list');
                            if (iHeader.length > 0 && lHeader.length > 0) {
                                if (iHeader.position().top <= lHeader.scrollTop()) {
                                    lHeader.scrollTop(iHeader.position().top - iHeader.height()/2);
                                } else if (iHeader.position().top + iHeader.height() > lHeader.scrollTop()
                                        + lHeader.height()) {
                                    lHeader.scrollTop(iHeader.position().top + 3*iHeader.height()/2 - lHeader.height());
                                }
                                if (i == 0) {
                                    lHeader.scrollTop(0);
                                } else if (jqContainer.scrollTop() >= $(document).height() - jqContainer.height()) {
                                    lHeader.scrollTop(lHeader.prop('scrollHeight') - lHeader.height());
                                }
                            }
                            break;
                        }
                    }
                }
            });
        }

        self.callback = function(height, width, refresh) {
            // Resize blog view
            setTimeout(function() {
                var jqContainer = $(window);
                if (jqContainer[0].scrollHeight > jqContainer.height()) {
                    $('.x-header-list').css('right', '');
                    $('.x-blog-sidebar').css('right', '');
                } else {
                    $('.x-header-list').css('right', '54px');
                    $('.x-blog-sidebar').css('right', '4px');
                }
            }, 250);
        }

        self.gotoTop = function() {
            $(window).scrollTop(0);
        }

        self.scrollTo = function(id, i) {
            if (self.selected != id) {
                $('.x-header-list li').removeClass('x-active');
                self.selected = id;
                anchorScrolled = false;
                $timeout(function() {
                    $anchorScroll(id);
                    $timeout(function() {
                        anchorScrolled = true; 
                    }, 50);
                }, 50);
            }
        }
    });
});
